<?php
require_once 'import/importer.inc';
require_once 'models/TCatalogProductModel.inc';
require_once 'models/TCMSPageCategoryModel.inc';
require_once 'models/TMSProductImageModel.inc';
require_once 'models/TMSProductSitePublisher.inc';

class TUcozImporter extends TConfigurable implements IImporter {
/**
 * @var TCatalogProductModel
 */	
	protected $_ioc_product_model_;
/**
 * @var TMSProductImageModel
 */	
	protected $_ioc_product_image_model_;
/**
 * @var TMSProductSitePublisher
 */	
	protected $_ioc_product_publisher_;
/**
 * @var TCMSStickerModel
 */	
	protected $_ioc_sticker_model_;
	
	public function Options(){
		return array(
			new TPropertyMeta('imagepath', 'Path to product images', TItemPropertyType::PT_STRING),
			new TPropertyMeta('importfile', 'File', TItemPropertyType::PT_FILE),
			new TPropertyMeta('defaultimage', 'Default image', TItemPropertyType::PT_IMAGE),
			new TPropertyMeta('offset', 'Offset', TItemPropertyType::PT_INT),
			new TPropertyMeta('count', 'Count', TItemPropertyType::PT_INT)
		);
	}
	
	public function Import(array $options = array()){
		$import_img_path = @$options['imagepath'];
		
		$man = array();
		$res = $this->_ioc_manufacturer_model_->GetList();
		foreach ($res as $m)
			$man[$m->Name] = $m->Id;
			
		$stickers = array();
		$res = $this->_ioc_sticker_model_->GetList();
		foreach ($res as $s)
			$stickers[$s->Code] = $s->Code;
			
		$ustates = array();
		$res = $this->ProductModel->ProductUnavailableStates();
		foreach ($res as $s)
			$ustates[$s->Name] = $s->Id;	

		$import_file = $options['importfile']->GetStorePath();
		$default_image = null;
		if (isset($options['defaultimage'])){
			$default_image = $options['defaultimage']->GetStorePath();
			$default_image = new TImage($this->Application(),basename($default_image),$default_image);
		}
		
		$db = dbase_open($import_file,0);
		if ($db){
			$fconv = create_function('&$item,$key','$item = iconv("cp866","UTF-8",$item);');
			$n = dbase_numrecords($db);
			$start = 1;
			if (isset($options['offset']))
				if ($options['offset'] < $n)
					$start = $options['offset'];
					else 
					$start = $n;
			if (isset($options['count']))
				if (($start + $options['count'] - 1) < $n)
					$n = $start + $options['count'] -1;
			
			for ($i = $start; $i <= $n; $i++){
				$row =  dbase_get_record_with_names($db, $i);
				array_walk($row, $fconv);
				if (is_array($row)){
					if (trim(@$row['MAN']) && !isset($man[@$row['MAN']])){
						$m = $this->_ioc_manufacturer_model_->CreateItem(array('Name'=>@$row['MAN']));
						$man[@$row['MAN']] = $m->Id;
					}
					$manid = isset($man[@$row['MAN']])?$man[@$row['MAN']]:null;
					if (trim(@$row['STICKER']) && !isset($stickers[trim(@$row['STICKER'])])){
						$s = $this->_ioc_sticker_model_->CreateItem(array('Code'=>@$row['STICKER'],'Title'=>@$row['STICKER']));
						$stickers[@$row['STICKER']] = @$row['STICKER'];
					}

					$ustate = isset($ustates[trim(@$row['USTATE'])])?$ustates[trim(@$row['USTATE'])]:null;
				
					$product = $this->ProductModel->CreateItem(array(
						'Name'=>trim(@$row['NAME']),
						'Price'=>trim(@$row['PRICE']),
						'Quantaty'=>1,
						'Sizes'=>trim(@$row['SIZE']),
						'Colors'=>trim(@$row['COLOR']),
						'Category'=>trim(@$row['CCID']),
						'Units'=>trim(@$row['UNIT']),
						'UnavailableState'=>$ustate,
						'Manufacturer'=>$manid
					));
				
					$page = $this->_ioc_product_publisher_->PublishProduct($product->Base, array(@$row['CID']));
					$page->Description = trim(@$row['SDESC']);
					$page->Contents = trim(@$row['DESC']);
					$page->Slug = trim(@$row['LINK']);
					$page->Snippet = trim(@$row['SDESC']);
					$page->Sticker = trim(@$row['STICKER']);
					$page->IsPublished = true; 
					$this->_ioc_product_publisher_->Save($page);

					$cover = true;
					$image_created = false;
					if (file_exists($import_img_path)){
						for ($j = 0; $j < 10; $j++){
							$filename = $import_img_path.trim($row['ID']).($j?('_'.$j):'').'.jpg';
							if (file_exists($filename)){
								$this->_ioc_product_image_model_->CreateItem(array(
									'Product'=>$product->Base,
									'Image'=>new TImage($this->Application(),basename($filename), $filename)
								));
								$image_created = true;
							}
						}
					}
					if (!$image_created && $default_image){
						$this->_ioc_product_image_model_->CreateItem(array(
							'Product'=>$product->Base,
							'Image'=>$default_image
						));
					}
				}
			}
			dbase_close($db);
		}
		unlink($import_file);
		if ($default_image)
			unlink((string)$default_image);					
	}
}